const mongoose = require('mongoose')
import conf from './config'

const DB_URL =  process.env.NODE_ENV === 'development' ? `mongodb://${conf.mongodb.host}:${conf.mongodb.port}/${conf.mongodb.db}` : `mongodb://${conf.mongodb.user}:${conf.mongodb.pwd}@${conf.mongodb.host}:${conf.mongodb.pport}/${conf.mongodb.db}`
mongoose.Promise = global.Promise

const options = {
  reconnectTries: Number.MAX_VALUE,
  reconnectInterval: 500
};

mongoose.connect(DB_URL, options)

const db = mongoose.connection;

db.once('open', () => console.log('数据库连接成功!'));
db.on('error', (err) => {
  console.log('数据库连接错误：', err);
  mongoose.disconnect();
});
db.on('close', () => {
  console.log('数据库连接断开，重新连接...');
  mongoose.connect(url, options);
});

export default mongoose
